package com.neusoft.bizcore.notice.conf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import com.neusoft.bizcore.web.utils.id.BaseIdGenerator;
import com.neusoft.bizcore.web.utils.id.DefaultIdGenerator;

@Configuration
@ComponentScan(basePackages = "com.neusoft.bizcore.notice")
public class BizcoreNoticeConfiguration {

    // 通知模板前缀
    private static final String NOTICE_TEMPLATE_PREFIX = "NT_";

    @Value("${bizcore.notice.threadSize: 10}")
    private int noticeThreadSize;

    @Value("${bizcore.notice.threadMaxSize: 100}")
    private int noticeThreadMaxSize;

    @Value("${bizcore.notice.keepAliveTime: 120}")
    private int noticeKeepAliveTime;

    @Value("${bizcore.notice.handlerQueue: 10000}")
    private int noticeHandlerQueue;

    @Value("${bizcore.notice.kafkaThreadSize: 10}")
    private int noticeKafkaThreadSize;

    @Value("${bizcore.notice.kafkaThreadMaxSize: 100}")
    private int noticeKafkaThreadMaxSize;

    @Value("${bizcore.notice.kafkaKeepAliveTime: 120}")
    private int noticeKafkaKeepAliveTime;

    @Value("${bizcore.notice.kafkaHandlerQueue: 10000}")
    private int noticeKafkaHandlerQueue;

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public BaseIdGenerator noticeTemplateCodeGenerator() {
        return new DefaultIdGenerator(0, BizcoreNoticeConfiguration.NOTICE_TEMPLATE_PREFIX);
    }

    @Bean("noticeDataExecutor")
    public ExecutorService asyncCollectionExecutorService() {
        final ExecutorService executorService = new ThreadPoolExecutor(
                Integer.valueOf(this.noticeThreadSize),
                Integer.valueOf(this.noticeThreadMaxSize),
                this.noticeKeepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(this.noticeHandlerQueue),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return executorService;
    }

    @Bean("noticeKafkaExecutor")
    public ExecutorService noticeKafkaExecutorService() {
        final ExecutorService executorService = new ThreadPoolExecutor(
                Integer.valueOf(this.noticeKafkaThreadSize),
                Integer.valueOf(this.noticeKafkaThreadMaxSize),
                this.noticeKafkaKeepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(this.noticeKafkaHandlerQueue),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return executorService;
    }
}
